package com.sl.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sl.springboot.entity.Audit;
import com.sl.springboot.entity.User;
import com.sl.springboot.exception.ServiceException;
import com.sl.springboot.mapper.UserMapper;
import com.sl.springboot.service.AuditService;
import com.sl.springboot.service.UserService;
import com.sl.springboot.utils.TokenUtils;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuditService auditService;
    @Override
    public User login(User user) throws ServiceException {
        User dbUser = selectByUserName(user.getUsername());
        if (dbUser == null) {
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        String token = TokenUtils.createToken(dbUser.getId().toString(),dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;

    }
    @Transactional
    @Override
    public void updateUserAndAudit(User user) {
        userMapper.updateById(user);
        List<Audit> auditList = auditService.getByUserId(user.getId());
        for (Audit audit : auditList) {
            audit.setPhone(user.getPhone());
            audit.setName(user.getName());
            audit.setUsername(user.getUsername());
            audit.setAvatar(user.getAvatar());
            audit.setEmail(user.getEmail());
            auditService.updateById(audit);

        }
    }

    public User selectByUserName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        return getOne(queryWrapper);
    }
}